package com.caipiao.crawler.shengfucang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caipiao.constant.CrawlerConstants;
import com.caipiao.crawler.mapper.LotteryFootballMapper;
import com.caipiao.crawler.model.LotteryFootball;
import com.caipiao.crawler.model.LotteryNumber;
import com.caipiao.crawler.page.BasePageProcessor;
import com.caipiao.util.DBTools;
import org.apache.ibatis.session.SqlSession;
import us.codecraft.webmagic.Page;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by adminitrator on 2018/7/28.
 */
public class ShengfucangDetailPage extends BasePageProcessor {

    SqlSession session = DBTools.getSession();
    LotteryFootballMapper mapper = session.getMapper(LotteryFootballMapper.class);

    @Override
    public void process(Page page) {
        String url = page.getUrl().toString();
        System.out.println(url);
        if(url.contains("history")) {
            processData(page);
        }else if(url.contains("_term=&")){
            //比赛数据
            processNowMatchTerm(page);
        }else if(url.contains("match_data")){
            //比赛数据
            processMatch(page);
        }
    }

    /**
     * 更新胜负场销售金额和奖金池
     * @param page
     */
    public void processData(Page page) {
        String id = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[1]/text()").toString();
        String total_sales = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[8]/text()").toString();
        String prize_pool = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[9]/text()").toString();
        String total_sales_9 = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[13]/text()").toString();
        LotteryNumber model = new LotteryNumber();
        model.setTerm(id);
       model.setTotal_sales(total_sales);
       model.setPrize_pool(prize_pool);
       model.setTotal_sales_9(total_sales_9);
        model.setUpdated_time((int) (System.currentTimeMillis()/1000L));
        model.setType(4);
        page.putField("model", model);
    }

    public void processNowMatchTerm(Page page){
        page.setSkip(true);
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        JSONObject lterm = obj.getJSONObject("lterm");
        String term = lterm.getString("term");
        String targetUrl = CrawlerConstants.SHENGFUCANG_NOW_URL.replace("qishu",term);
        page.addTargetRequest(targetUrl);
    }

    /**
     * 更新胜负场赔率已经赛事结果
     * @param page
     */
    public void processMatch(Page page) {
//        page.setSkip(true);  //不需要传到pipeline
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        LotteryNumber model = new LotteryNumber();
        JSONObject lterm = obj.getJSONObject("lterm");
        model.setTerm(lterm.getString("term"));
//        model.setDetails(obj.getString("match_vs"));
        model.setCreated_time((int) (System.currentTimeMillis()/1000L));
        model.setType(4);
        JSONArray array =  obj.getJSONArray("match_vs");
        //关联赔率
        for(int i=0;i<array.size();i++){
            JSONObject match = (JSONObject) array.get(i);
            String homeTeamView = match.getString("homeTeamView");
            String awayTeamView = match.getString("awayTeamView");
            String matchname = match.getString("matchname");
            String matchTime = match.getString("matchTime");
            Map map = new HashMap();
//            map.put("first_team",homeTeamView);
//            map.put("second_team",awayTeamView);
            map.put("match_type",matchname);
            map.put("date",matchTime.replace("月","-").replace("日",""));
            String sfcTeamInfo = homeTeamView+awayTeamView; //胜负彩球队信息
            List<LotteryFootball> footballList =  mapper.selectDetailsForSfc(map);
            int countP =0;
            String plDetail ="";
            String jczqMatchTime = "";
            for(LotteryFootball lotteryFootball :footballList){
                String firstTeam = lotteryFootball.getFirst_team();
                String secondTeam = lotteryFootball.getSecond_team();
                String jczqTeamInfo = firstTeam+secondTeam; //竞彩足球球队信息
                int count = 0;
                for(int m=0;m<sfcTeamInfo.length();m++){
                    if(jczqTeamInfo.contains(String.valueOf(sfcTeamInfo.charAt(m)))){
                        count++;
                    }
                }
                if(count>countP) {
                    countP = count;
                    plDetail = lotteryFootball.getDetails();
                    jczqMatchTime = lotteryFootball.getDate();
                }
            }
            System.out.println(countP);
            System.out.println(plDetail);
            JSONObject plJson = JSONObject.parseObject(plDetail);
            if(plJson!=null) {
                plJson.getString("detail2");
                match.put("sheng", plJson.getJSONObject("detail2").getString("胜"));
                match.put("ping", plJson.getJSONObject("detail2").getString("平"));
                match.put("fu", plJson.getJSONObject("detail2").getString("负"));
                match.put("matchTime", jczqMatchTime);
            }
        }
        model.setDetails(array.toString());
        System.out.println("-------------------------");
        System.out.println(model.getDetails());
        page.putField("model", model);
    }

}
